<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>{{ $t('Home') }}</el-breadcrumb-item>
    <el-breadcrumb-item>{{ $t('Profile') }}</el-breadcrumb-item>
  </el-breadcrumb>
  <el-container class="profile-page">
    <el-main>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>{{ $t('profile.basicInfo') }}</span>
            <el-button type="primary" @click="save">{{ $t('profile.save') }}</el-button>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="6" style="display: flex; justify-content: center; align-items: center;">
            <el-avatar :size="100" :src="config.getUrl(user.avatar_url)" @click="triggerFileInput" @error="() => true" >
              <img src="../assets/images/user.png" />
            </el-avatar>
            <input type="file" ref="fileInput" @change="uploadAvatar" accept="image/*" style="display: none;" />
          </el-col>
          <el-col :span="18">
            <el-descriptions :column="2" border>
              <!-- 密钥名称 -->
              <el-descriptions-item :label="$t('keyName')">
                <el-input v-model="key_name" disabled/>
              </el-descriptions-item>

              <!-- 密钥名称 -->
              <el-descriptions-item :label="$t('keyAddress')">
                <el-input v-model="key_address" disabled/>
              </el-descriptions-item>

              <!-- 用户名 -->
              <el-descriptions-item :label="$t('profile.username')">
                <el-input v-model="user.username" />
              </el-descriptions-item>

              <!-- 创建时间 -->
              <el-descriptions-item :label="$t('profile.createdAt')">
                <el-input v-model="user.created_at" disabled />
              </el-descriptions-item>

              <!-- 账户地址 -->
              <el-descriptions-item :label="$t('profile.accountAddress')" :span="2">
                <el-input v-model="user.account_address" disabled/>
              </el-descriptions-item>

              <!-- 个人简介 -->
              <el-descriptions-item :label="$t('profile.bio')" :span="2">
                <el-input v-model="user.bio" type="textarea" :rows="4"/>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-card>
    </el-main>
  </el-container>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElAvatar, ElCard, ElInput, ElButton, ElRow, ElCol, ElContainer, ElMain } from 'element-plus';
import { useI18n } from 'vue-i18n';
import eventBus from '@/utils/eventbus';
import ApiClient from '@/api/ApiClient';
import { ApiRequest, ApiRequestBody } from '@/api/ApiRequest';
import { ApiResponse } from '@/api/ApiResponse';
import { config } from '@/config/config';
import { User } from '@/model/User';
import { ipfsClient } from '@/api/IPFSClient';

const user: User = reactive({
  avatar_url: '',
  username: '',
  bio: '',
  account_address: '',
  created_at: ''
});

const { t } = useI18n();
const key_name = ref(localStorage.getItem('key_name'));
const key_address = ref(localStorage.getItem('key_address'));

onMounted(() => {
  const request = new ApiRequest(
    "query",
    config.dao_chain_name,
    new ApiRequestBody(
      config.dao_contract_name,
      "get_user",
      {}
    )
  );
  ApiClient.sendSync(request, (response: ApiResponse) => {
    if (response.status === 200 && response.data.contract_result.code === 0) {
      const data = JSON.parse(response.data.contract_result.result)[0];
      if(data){
        user.avatar_url = data.avatar_url || user.avatar_url;
        user.username = data.username || user.username;
        user.bio = data.bio || user.bio;
        user.account_address = data.account_address || user.account_address;
        user.created_at = formatDate(data.created_at);
        localStorage.setItem("user", JSON.stringify(user));
        eventBus.emit('userChange', user);
      }
    } else {
      ElMessage.error(t('queryUserFailure'));
    }
  });
});

const formatDate = (unixTimestamp: number): string => {
  const date = new Date(unixTimestamp * 1000);
  return date.toISOString().replace('T', ' ').substring(0, 19);
};

const save = () => {
  const request = new ApiRequest(
    "invoke",
    config.dao_chain_name,
    new ApiRequestBody(
      config.dao_contract_name,
      "save_user",
      {
        "username": user.username,
        "avatar_url": user.avatar_url,
        "bio": user.bio
      }
    )
  );
  ApiClient.sendSync(request, (response: ApiResponse) => {
    if (response.status === 200 && response.data.contract_result.code === 0) {
      ElMessage.success(response.data.contract_result.result);
    } else {
      ElMessage.error(t('queryUserFailure'));
    }
  });
};

const fileInput = ref<HTMLInputElement | null>(null);
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};
const uploadAvatar = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    try {
      const result = await ipfsClient.add(file);
      user.avatar_url = `ipfs://${result.path}`;
      ElMessage.success(t('uploadSuccess'));
    } catch (error) {
      ElMessage.error(t('uploadFailed'));
      console.error(error);
    }
  }
};
</script>

<style scoped>
.profile-page {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-card {
  margin-bottom: 20px;
}
</style>